import { View, Text, ScrollView, Image, Button, Input } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import nodata from '@/static/nodata.png'
import { useInfiniteScroll, useSetState, useMemoizedFn, useBoolean } from 'ahooks'
import { getInviteList, getApplyList, saveApply } from '@/api' 
// import { useState } from 'react'

import './index.scss'

export default function Invite() {

  const [tabIndex, setTabIndex] = useSetState(
    {
      index: 0
    }
  )

  const [showDeviceForm, { setFalse, setTrue }] = useBoolean(false)

  const [applyData, setApplyData] = useSetState({})

  const [form, setForm] = useSetState({
    id: '',
    name: '',
    phone: '',
    address: '',
    biz_name: '',
  })

  const {
    data: { total = 0, list: dataList = [], earn = 0, rmb = 0 } = {},
    loading: initLoading,
    loadMore,
  } = useInfiniteScroll((d) => {
    // console.log(123)

    const page = d ? Math.ceil(d.list.length / 10) + 1 : 1;
      return getInviteList({
        size: 10,
        page
      }).then(res => ({ list: res?.data || [], total: res?.total || 0, earn: res?.earn, rmb: res?.rmb }))
  }, {
    isNoMore: (res) => res?.list?.length >= res?.total || false,
    onSuccess(res) {
      console.log(res)
    }
  })

  const loadApplyList = () => {
    getApplyList().then(res => {
      // console.log(res);
      setApplyData({...res});
    });
  }

  const selectTab = (idx) => {
    setTabIndex({index: idx})
    if (idx == 1) {
      loadApplyList()
    }
  }

  const onSave = () => {
    // console.log(form);
    if (!form?.name) return Taro.showToast({ title: '收货人不能为空', icon: 'none' })
    if (!form?.phone) return Taro.showToast({ title: '收货人电话不能为空', icon: 'none' })
    if (!form?.address) return Taro.showToast({ title: '收货地址不能为空', icon: 'none' })
    if (!form?.biz_name) return Taro.showToast({ title: '业务员姓名不能为空', icon: 'none' })

    saveApply({
      id: form.id || '',
      payload: JSON.stringify({...form})
    }).then(res => {
      if (res?.code == 0) {
        setFalse()
        Taro.showToast({ title: '提交成功', icon: 'success' })
        loadApplyList()
      }
      
    });
  }

  const copyItem = (item) => {
    Taro.setClipboardData({
      data: `${item.exp_name} ${item.exp_no}`,
      success: () => {
        Taro.showToast({ title: '复制成功', icon: 'success' })
      }
    })
  }

  const newItem = () => {
    setForm({
      id: '',
      name: '',
      phone: '',
      address: '',
      biz_name: ''
    })
    setTrue()
  }

  const editItem = (item) => {
    setForm({...item})
    setTrue()
  }

  return (
    <View className='index-box'>
      <View className='list-box'>
        {
          total === 0 && !initLoading ? (
            <View className='flex-direction flex-center' style={{ "height": '75vh' }}>
              <Image style={{ width: '100rpx' }} mode='widthFix' src={nodata}></Image>
              <View className='text-ds text-99 margin-top-sm'>暂无数据</View>
            </View>
          ) : (
             <ScrollView
               className='scrollview'
               scrollY
               scrollWithAnimation
               style={{
                  height: '100vh'
                }}
               lowerThreshold={20}
               onScrollToLower={loadMore}
             >
              <View className='total-stats'>
                <View className='score'>
                  <View className='label'>奖励积分</View>
                  <View className='value'>{earn || 0}</View>
                </View>
                <View className='money'>
                  总交易：{ rmb || 0 }元
                </View>
                <Button className='cu-btn bg-blue main-bc round margin-top-xs' onClick={() => Taro.navigateTo({ url: '/pages/withdraw/index' })}>去提现</Button>

              </View>

              <View className='tabs'>
                <View className={`tab ${ tabIndex.index == 0 ? 'active' : '' }`} onClick={() => selectTab(0)}>
                  我的下级({total})
                </View>
                <View className={`tab ${ tabIndex.index == 1 ? 'active' : '' }`} onClick={() => selectTab(1)}>
                  申请的设备({applyData?.data?.length || 0})
                </View>
              </View>
              
              { tabIndex.index == 0 && dataList?.map?.((item, index) => (
                <View key={item?.id} className={`flex padding-sm ${index % 2 === 1 ? 'bg-white' : 'bg-gray'}`}>
                  <View className='flex-sub'>
                    <View className='margin-bottom-xs text-df'>设备SN号：<Text className='text-red text-dl'>{item?.sn}</Text></View>
                    {/* <View className='text-sm text-66'>设备SN号：{item?.sn}</View> */}
                    <View className='text-sm text-66'>邀请时间：{item?.invite_time}</View>
                    <View className='text-sm text-66'>总交易量：{item?.invite_money || '0'}元</View>
                    <View className='text-sm text-66'>积分奖励：{item?.invite_score || '0'}积分</View>
                    {/* <View className='text-sm text-66' style="color:red;font-size: 32rpx;">{item?.memo}</View> */}
                  </View>
                </View>
              ))}
              {
                tabIndex.index == 1 && <View className='apply-box'>
                  <Button className='cu-btn main-borderc main-color line-blue round margin block' onClick={newItem}>新增设备</Button>
                  <View className='list'>
                    {
                      applyData?.data?.map?.((item,index) => (
                        <View className='a-item' key={index}>
                          <View className='left'>
                            <View className='name'>{item.name} {item.phone}</View>
                            <View className='addr'>邮寄地址：{item.address}</View>
                            <View className='time'>发货时间：{item.ship_time || '未发货'}</View>
                            { item.exp_no && <View className='info' onClick={() => copyItem(item)}>快递信息：{item.exp_name} {item.exp_no} 复制</View>}
                            <View className='time'>业务员姓名：{item.biz_name}</View>
                          </View>
                          <View className='right'>
                            { !item.exp_no && <Button className='cu-btn main-color bg-white' onClick={() => editItem(item)}>编辑</Button> }
                          </View>
                        </View>
                      ))
                    }
                  </View>
                </View>
              }
                <View className={`cu-load ${dataList?.length >= total ? 'over' : 'loading'}`}></View>
            </ScrollView>
          )
        }
      </View>

      <View className={`cu-modal ${showDeviceForm ? 'show' : ''}`} onClick={setFalse}>
        <View className='cu-dialog' onClick={e => e?.stopPropagation()}>
          <View className='form-box'>
          <View className='flex margin-bottom-sm bottom-line'>
            <Text className='margin-right-sm f-label'>收货人</Text><br/>
            <Input className='flex-sub' value={form.name} onInput={e => setForm({ name: e?.target?.value || '' })} placeholder='请输入收货人' />
          </View>
          <View className='flex margin-bottom-sm bottom-line'>
            <Text className='margin-right-sm f-label'>收货人电话</Text><br/>
            <Input className='flex-sub' value={form.phone} onInput={e => setForm({ phone: e?.target?.value || '' })} placeholder='请输入收货人电话' />
          </View>
          <View className='flex margin-bottom-sm'>
            <Text className='margin-right-sm f-label'>收货地址</Text><br/>
            <Input className='flex-sub' value={form.address} onInput={e => setForm({ address: e?.target?.value || '' })} placeholder='请输入收货地址' />
          </View>
          <View className='flex margin-bottom-sm'>
            <Text className='margin-right-sm f-label'>业务员姓名</Text><br/>
            <Input className='flex-sub' value={form.biz_name} onInput={e => setForm({ biz_name: e?.target?.value || '' })} placeholder='请输入业务员姓名' />
          </View>
          </View>
          
          <View className='flex-center'>
            <Button
              onClick={onSave}
              className='main-bc text-lg text-center margin padding-lr-xl round line-white'
              formType='submit'
            >
              &emsp;确认提交&emsp;
            </Button>
          </View>
        </View>
      </View>
    </View>
  )
}
